package com.proj.controller;


import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alipay.api.AlipayApiException;
import com.proj.bean.*;
import com.proj.service.ICartService;
import com.proj.service.impl.OrderService;
import com.proj.util.LayData;
import com.proj.util.Page;
import com.proj.util.PaymentUtil;
import com.proj.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@Controller
@RequestMapping("order")
public class OrderController {

    @Autowired
    ICartService cartService;

    @Autowired
    OrderService orderService;

    @ResponseBody
    @RequestMapping("add")
    public int addOrder(HttpSession session){
        Order order = new Order();
        //时间戳 + 自增序列（线程安全）
        //精确到毫秒，同一毫秒内最多生成999个订单。线程安全，适合单机高并发场景。重启应用可能导致序列重置（同一毫秒可能重复，但概率极低）。
        // 自增序列，每日重置
        AtomicLong sequence = new AtomicLong(0);
        // 日期格式化（精确到毫秒）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timestamp = sdf.format(new Date());
        long seq = sequence.incrementAndGet() % 1000; // 限制序列长度
        String ordercode=timestamp + String.format("%03d", seq);
        order.setCode(ordercode);
        BigDecimal total = new BigDecimal(0);

        int userid=((User) session.getAttribute(SYS.SHOPPING_LOGIN_USER)).getId();
        order.setUserid(userid);
        try{
            List<Cart> cart = cartService.getList(userid);
            List<Orderinfo> infos= new ArrayList<>(cart.size());
            for (Cart value : cart) {
                if(value.getSelected()==1){
                    Orderinfo info = new Orderinfo();
//            info.setOrderid();
                    info.setGoodsid(value.getGoodsid());
                    info.setGoodsname(value.getGoods().getName());
                    info.setNumber(value.getNumber());
                    info.setImgurl(value.getGoods().getDefaultimg());
                    info.setPrice(value.getGoods().getPrice());
                    infos.add(info);
                    total = total.add((info.getPrice()).multiply(BigDecimal.valueOf(info.getNumber())));
                }
            }
            order.setMoney(total);
            order.setInfos(infos);
            order.setState(0);

            Orderaddress address = new Orderaddress();
//        address.setOrderid(1);
            Useraddress useraddress = orderService.getAddress(userid);
            address.setName(useraddress.getName());
            address.setTelephone(useraddress.getTelephone());
            address.setAddress(useraddress.getProvince()+"-"+useraddress.getCity()+"-"+useraddress.getArea()+"-"+useraddress.getAddress());
            order.setAddress(address);

            orderService.addOrder(order);
            orderService.addOrderInfo(order);
            orderService.addOrderAddress(order);
            //获取order
            //添加order内容
            //删除cart
        }catch(Exception e){
            System.out.println("userid:"+userid+";code:"+ordercode);
            e.printStackTrace();
            return -1;
        }
        orderService.OrderDelCart(userid);
        return order.getId();
    }

//    @ResponseBody
//    @RequestMapping("payment")
//    public BigDecimal payment(HttpSession session) {
//        return null;
//    }

    @ResponseBody
    @RequestMapping("easyOrder")
    public List<Order> easyOrder(HttpSession session) {
        return orderService.easyOrder(SYS.getLoginUserID(session));
    }

    @ResponseBody
    @RequestMapping("allOrder")
    public LayData allOrder(Page page, String text) {
        List<Order> order = orderService.allOrder(page,text);
        int count = orderService.allOrdercount(text);
        return new LayData(count, order);
    }

    @ResponseBody
    @RequestMapping("getMoneyByOrderid")
    public Order getMoneyByOrderid(Integer orderid) {
        return orderService.getMoneyByOrderid(orderid);
    }

    @ResponseBody
    @RequestMapping("getQR")
    public String getQR(Integer orderid) {
        Order order = orderService.getMoneyByOrderid(orderid);
        String url=null;
        try {
            url=PaymentUtil.payment(order);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //生成二维码图片
        BufferedImage img = QrCodeUtil.generate(url,300,300);
        //转换成Base64编码
        String qrcode=ImgUtil.toBase64(img,"png");
        return qrcode;
    }

    @ResponseBody
    @RequestMapping("zhifu")
    public int zhifu(int orderid) {
        return orderService.zhifu(orderid);
    }

    @ResponseBody
    @RequestMapping("send")
    public int send(int orderid) {
        return orderService.send(orderid);
    }

    @ResponseBody
    @RequestMapping("shouhuo")
    public int shouhuo(int orderid) {
        return orderService.shouhuo(orderid);
    }

    @ResponseBody
    @RequestMapping("jieshu")
    public int jieshu(int orderid) {
        return orderService.jieshu(orderid);
    }

    @ResponseBody
    @RequestMapping("roseinfos")
    public List<Orderinfo> roseinfos(){
        return orderService.roseinfos();
    }






    //以下一段代码已失效
//    @ResponseBody
//    @RequestMapping("added")
//    public LayData add(@RequestParam("id")List<Integer> id,@RequestParam("number")List<Integer> number, HttpSession session){
//        //http://localhost:8080/order/added?id=1,2,3&number=4,5,6
//        //如果运行不了，在@RequestParam("id")里面加上[]，@RequestParam("number[]")
//        System.out.println(id);
//        System.out.println(number);
//        System.out.println(session.toString());
//        return null;
//    }

}
